<template>
  <div class="history">
    <el-card shadow="never">
      <el-form :inline="true" :model="query">
        <el-form-item label="文件名">
          <el-input v-model="query.search.name" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item v-if="false" label="文件路径">
          <el-input v-model="query.search.localPath" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="同步状态">
          <el-select v-model="query.search.status" style="width: 180px" filterable clearable>
            <el-option
              v-for="status in statuses"
              :key="status.value"
              :label="status.name"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="添加日期">
          <el-date-picker
            v-model="query.search.createdAt"
            type="daterange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
            value-format="x"
            :shortcuts="shortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="paginate()" native-type="button">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-divider></el-divider>
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>同步记录</h3>
        </div>
      </template>
      <el-table
        :border="true"
        :data="page.records"
        v-loading="page.loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="#" width="100" />
        <el-table-column prop="name" label="文件名称" width="180" />
        <el-table-column prop="size" label="文件大小" width="120">
          <template #default="scope">
            {{ filesize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="modified" label="文件修改时间" width="200">
          <template #default="scope">
            {{ formatToLocaleString(scope.row.modified) }}
          </template>
        </el-table-column>
        <el-table-column prop="localPath" label="本地路径" width="320" />
        <el-table-column prop="remotePath" label="远程路径" width="320" />
        <el-table-column prop="status" label="同步状态" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row['status'] === 0" type="info"> 待同步</el-tag>
            <el-tag v-else-if="scope.row['status'] === 1" type="success"> 已同步</el-tag>
            <el-tag v-else-if="scope.row['status'] === 2" type="danger"> 失败</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="syncedAt" label="同步时间" width="200">
          <template #default="scope">
            {{ formatToLocaleString(scope.row.syncedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="添加时间" width="200">
          <template #default="scope">
            {{ formatToLocaleString(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="onDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="query.currentPage"
        v-model:page-size="query.pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="page.total"
        @currentChange="paginate()"
        @sizeChange="paginate()"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </el-card>
  </div>

  <el-dialog v-model="detailModel.visible" title="同步详情" width="80%">
    <el-table :data="detailModel.data" :show-header="false">
      <el-table-column prop="column" label="Column" width="120">
        <template #default="scope">
          <el-text truncated>{{ scope.row.column }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="value" label="Value">
        <template #default="scope">
          <div v-if="scope.row.key == 'status'">
            <el-tag v-if="scope.row.value === 0" type="info"> 待同步</el-tag>
            <el-tag v-else-if="scope.row.value === 1" type="success"> 已同步</el-tag>
            <el-tag v-else-if="scope.row.value === 2" type="danger"> 失败</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </div>
          <div v-else>{{ scope.row.value }}</div>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import { onBeforeMount, ref } from 'vue'
import { backendService, ResponseCode } from '@/service/BackendService'
import { formatToLocaleString } from '@/service/DateService'
import { filesize } from 'filesize'

const statuses = [
  { value: 0, name: '待同步' },
  { value: 1, name: '已同步' },
  { value: 2, name: '失败' }
]
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]
const query = ref({
  currentPage: 1,
  pageSize: 20,
  search: {
    name: undefined,
    localPath: undefined,
    status: undefined,
    createdAt: []
  }
})

const page = ref({
  loading: false,
  total: 0,
  records: [],
  extra: {}
})

// 定义数组中元素的类型
interface DataType {
  key: string
  column: string
  value: any
}

const detailModel = ref<{
  visible: boolean
  data: DataType[] // data 是 DataType 数组
}>({
  visible: false,
  data: []
})

const paginate = () => {
  page.value.loading = true
  backendService
    .post('/api/history', query.value)
    .then((response) => {
      let data = response.data
      if (data.code === ResponseCode.OK) {
        Object.assign(page.value, data.data)
      }
    })
    .catch((error: any) => {
      ElNotification({
        title: 'Error',
        message: error,
        type: 'error',
        dangerouslyUseHTMLString: true
      })
    })
    .finally(() => {
      page.value.loading = false
    })
}

const onDetail = (row: any) => {
  detailModel.value.visible = true
  detailModel.value.data = [
    { key: 'id', column: '#', value: row['id'] },
    { key: 'name', column: '文件名', value: row['name'] },
    { key: 'size', column: '文件大小', value: `${row['size']} (${filesize(row['size'])})` },
    { key: 'modified', column: '文件修改时间', value: formatToLocaleString(row['modified']) },
    { key: 'localPath', column: '本地路径', value: row['localPath'] },
    { key: 'remotePath', column: '远程路径', value: row['remotePath'] },
    { key: 'status', column: '同步状态', value: row['status'] },
    { key: 'message', column: '同步信息', value: row['message'] },
    { key: 'syncedAt', column: '同步时间', value: formatToLocaleString(row['syncedAt']) },
    { key: 'createdAt', column: '创建时间', value: formatToLocaleString(row['createdAt']) }
  ]
}

onBeforeMount(() => {
  paginate()
})
</script>
